package com.dh.leetcode.zero;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;

/**
 * @ClassName: _59_spiral_matrix_ii
 * @Description: 59. 螺旋矩阵 II
 * 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
 * <p>
 * 构造矩阵返回
 * <p>
 * 输入：n = 3
 * 输出：[[1,2,3],[8,9,4],[7,6,5]]
 *
 * <p>
 * https://leetcode-cn.com/problems/spiral-matrix-ii/
 * @Author: shouzimu
 * @Date: 2021/3/16 9:40
 */
public class _59_spiral_matrix_ii {

    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int startX = 0, startY = 0, endX = n - 1, endY = n - 1;
        int v = 1;
        while (startX <= endX && startY <= endY) {
            //左到右
            for (int i = startX; i <= endX; i++) {
                matrix[startY][i] = v++;
            }
            startY++;
            //上到下
            for (int i = startY; i <= endY; i++) {
                matrix[i][endX] = v++;
            }
            endX--;
            //右到左
            for (int i = endX; i >= startX && startY <= endY; i--) {
                matrix[endY][i] = v++;
            }
            endY--;
            //下到上
            for (int i = endY; i >= startY && startX <= endX; i--) {
                matrix[i][startX] = v++;
            }
            startX++;
        }
        return matrix;
    }

    @Test
    public void generateMatrixTest() {
        Assert.assertEquals(Arrays.deepToString(new Integer[][]{{1, 2, 3}, {8, 9, 4}, {7, 6, 5}}),
                Arrays.deepToString(generateMatrix(3)));

        Assert.assertEquals(Arrays.deepToString(new Integer[][]{{1}}),
                Arrays.deepToString(generateMatrix(1)));
    }

}
